import requests
from calc_manager.base.plugins import PluginObject
from pyNastran.bdf.bdf import BDF
from io import StringIO

# read bdf model file
class BDFReader(PluginObject):
    def __init__(self, oss_url_list, entry_file_name = None, local_path = None) -> None:
        # init here to avoid global stat to operator
        self.reader = BDF()
        
        if local_path:
            self.reader.read_bdf(local_path, punch=True, validate=False)
        else:
            for oss_url in oss_url_list:
                response = requests.get(oss_url)
                response.raise_for_status()
                file_name = oss_url.split('/')[-1]
                with open(f'/tmp/{file_name}', 'wb') as f:
                    f.write(response.content)
                    print(f"Downloaded {file_name} from {oss_url} and saved to /tmp/{file_name}")

            if not entry_file_name:
                raise ValueError("entry_file_name is required when oss_url_list is not None")

            #bdf_data = StringIO(response.text)
            #self.reader.read_bdf(bdf_data)
            bdf_path = f'/tmp/{entry_file_name}'
            self.reader.read_bdf(bdf_path, punch=True, validate=False)
            #self.reader.read_bdf(bdf_path, punch=False, validate=False)
            print(f"bdf reader init......, entry_file_name: {entry_file_name}")

    def get_element_ids(self) -> list[int]:
        return list(self.reader.element_ids)

    def get_element_fields_by_id(self, eid) -> dict:
        element = self.reader.Element(eid)
        # 第一个元素是网格类型 eg. CQUAD4
        # 第二个元素是单元编号 eid
        # 第三个元素是属性编号 eg. 1
        # 暂时只取这是两个占位符数据 ['CQUAD4', 100, 1, 1218, 1225, 1264, 1255, 0.0, 0.0, None, 0, None, None, None, None]
        fields = element.raw_fields()
        prop_id = fields[2]
        prop_name = self.reader.properties[prop_id].type
        # 材料id取material_ids第一个
        mat_id = element.pid_ref.material_ids[0]
        return {
            "element_type": fields[0],
            "element_mid": mat_id,
            "element_prop": prop_name,
        }
    def get_element(self, refine_eids):
        return self.reader.Element(refine_eids)